<template>
	<div :class="curClassName" :style="curStyle" @click="handleClick">
		<img :src="dynaImgUrl" />
	</div>
</template>
<script setup lang="ts">
import { IEvent } from '@/core';
import { FieldImageDynamicProps } from './field-image-dynamic';
const props = defineProps(FieldImageDynamicProps);
interface ImageDynamicEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const emit = defineEmits<ImageDynamicEmit>();
/**
 * 项名称
 *
 * @memberof FieldImageDynamic
 */
const itemName = computed(() => {
	return props.index || props.index === 0
		? `${props.name}_${props.index}`
		: props.name;
});

/**
 * 当前容器样式
 *
 * @memberof FieldImageDynamic
 */
const curStyle = computed(() => {
	const layoutModel = props.layoutModelDetails[itemName.value];
	if (layoutModel) {
		return layoutModel.getElementStyle();
	}
});

/**
 * 类名
 *
 * @memberof FieldImageDynamic
 */
const curClassName = computed(() => {
	const layoutModel = props.layoutModelDetails[itemName.value];
	const classNames = {
		'app-field-image-dynamic': true,
	};
	if (layoutModel) {
		Object.assign(classNames, layoutModel.getClassNames());
	}
	return classNames;
});

/**
 * 动态图片路径
 *
 * @memberof AppFieldImageDynamic
 */
const dynaImgUrl = ref('');

/**
 * 下载文件路径
 *
 * @memberof AppFieldImageDynamic
 */
const downloadUrl = App.getProjectSetting().exportFileUrl;

/**
 * 处理动态图片
 *
 * @memberof AppFieldImageDynamic
 */
const handleDynaImg = () => {
	if (props.value && typeof props.value == 'string') {
		// 默认识别文件对象形式，识别失败则为全路径模式
		try {
			const _files = JSON.parse(props.value);
			const file = _files instanceof Array ? _files[0] : null;
			const url = file && file.id ? `${downloadUrl}/${file.id}` : '';
			dynaImgUrl.value = url;
		} catch (error) {
			dynaImgUrl.value = props.value;
		}
	}
};

watch(
	() => props.value,
	() => {
		handleDynaImg();
	}
);

/**
 * 处理点击
 * @param $event
 * @memberof AppFieldImageDynamic
 */
const handleClick = ($event: any) => {
	emit('component-action', {
		name: props.name,
		action: 'panelItemClick',
		data: $event,
	});
};
</script>
